package com.lagou.edu.service.impl;

import com.lagou.edu.pojo.LagouAuthCode;
import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.service.LaGouServiceEmailClient;
import com.lagou.edu.util.CodeUtil;
import com.lagou.edu.util.DateUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author: jie.zhao
 * @create: 2021/07/27 14:10
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Resource
    LagouAuthCodeDao lagouAuthCodeDao;

    @Resource
    LaGouServiceEmailClient laGouServiceEmailClient;

    @Override
    public Integer sendCode(String email) {
        String code = CodeUtil.produceCode(5);
        Date date = new Date();
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setCreatetime(date);
        lagouAuthCode.setCode(code);
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setExpiretime(DateUtil.getAfterDateIMinute(date,10));
        lagouAuthCodeDao.save(lagouAuthCode);
        laGouServiceEmailClient.sendCode(email,code);
        return Integer.parseInt(code);
    }

    @Override
    public Integer validate(String email, String code) {
        Date date = new Date();
        LagouAuthCode lagouAuthCode = lagouAuthCodeDao.findByEmailAndCode(email,code);
        if(lagouAuthCode==null){
            return 1;
        }
        if(date.after(lagouAuthCode.getExpiretime())){
            return 2;
        }
        return 0;
    }


}
